using System;
using System.Net;
using System.Windows.Forms;
using System.ServiceProcess;
using System.Collections.Generic;
using System.Drawing;

namespace ServerState
{
    public partial class MainForm : Form
    {
        // The backgroud color (and the transparency key) of the main form 
        // should be "Desktop". When using an other color, Win Vista has a problem
        // to smooth the screen font.  

        // List of all services. Only display the service state when the service is installed
        // Can be overwritten by command line parameters
        private static string[] serviceNames = new string[] { 
            "IpPbxSrv", "IpPbxCDS", "IpPbxReport", "HwDSrv", 
            "IpPbxGate", "LinkMgr", "PhoneController", "PhoneMgr",  
            "ConferenceMgr", "QueueManager", "MSSQLSERVER" };

        // List of current installed services
        private List<ServiceController> serviceList;

        /// <summary>
        /// Constructor of the main form. 
        /// Set text of all static (not changed during runtime) fields (machine name, IP addresses, 
        /// current user) and start the timer.
        /// </summary>
        public MainForm()
        {
            InitializeComponent();

            #region Create list of installed Services
            {
                this.serviceList = new List<ServiceController>();

                string[] services = MainForm.serviceNames;

                // Overwrite with service list from command line 
                // First entry is the executable name and will be ignored by the loop
                if (Environment.GetCommandLineArgs().Length > 1)
                    services = Environment.GetCommandLineArgs();

                foreach (string srv in services)
                {
                    try
                    {
                        ServiceController sc = new ServiceController(srv);

                        // Property throws an exception, wenn the service is not installed
                        ServiceControllerStatus st = sc.Status;

                        // Add the service to the list of current installed services
                        this.serviceList.Add(sc);
                    }
                    catch { }
                }
            }
            #endregion

            #region Fill the list view
            {
                // Add this items to the first list view group
                ListViewGroup lvGroup = this.listViewMain.Groups[0];
                ListView.ListViewItemCollection lvCol = this.ListViewColumn.ListView.Items;

                // Clear the list view
                lvCol.Clear();

                // Write the computer name
                lvCol.Add(new ListViewItem("Computer Name:", lvGroup)).
                    SubItems.Add(Environment.MachineName);

                // Write the DNS name when the machine name is different
                if (Dns.GetHostName().ToLower() != Environment.MachineName.ToLower())
                {
                    lvCol.Add(new ListViewItem("DNS Name:", lvGroup)).
                        SubItems.Add(Dns.GetHostName());
                }

                // Write the IP Addresses
                IPHostEntry IPs = Dns.GetHostEntry(Dns.GetHostName());
                string ipList = "";
                string ipDesc = (IPs.AddressList.Length > 1) ? "IP Addresses:" : "IP Address:";
                foreach (IPAddress IP in IPs.AddressList)
                {
                    if (ipList.Length != 0)
                        ipList += ", ";

                    ipList += IP;
                }
                lvCol.Add(new ListViewItem(ipDesc, lvGroup)).SubItems.Add(ipList);

                // Write the user name
                string userName = Environment.UserName;
                if (Environment.UserDomainName != Environment.MachineName)
                {
                    // Display a domain account as DOMAIN\USER
                    userName = string.Format("{0}\\{1}", Environment.UserDomainName, userName);
                }
                lvCol.Add(new ListViewItem("Current User:", lvGroup)).
                    SubItems.Add(userName);

                // Write the service states
                UpdateServiceState();
            }
            #endregion

            // Start the timer
            timer.Start();
        }

        /// <summary>
        /// Update the list view with the current state of the installed services
        /// </summary>
        private void UpdateServiceState()
        {
            ListViewGroup lvGroup = this.listViewMain.Groups[1];
            ListView.ListViewItemCollection lvCol = this.ListViewColumn.ListView.Items;

            // Remove all items from the list view where the 
            // item is member of the group "service"
            foreach (ListViewItem lvI in lvCol)
            {
                if (lvI.Group == lvGroup)
                    lvI.Remove();
            }

            // Add the current state of all sevices to the list
            foreach (ServiceController sc in this.serviceList)
            {
                sc.Refresh();
                lvCol.Add(new ListViewItem(sc.DisplayName + ":", lvGroup)).
                        SubItems.Add(sc.Status.ToString());
            }
        }

        /// <summary>
        /// Handler for the Close button.
        /// </summary>
        /// <param name="sender">Source of the event.</param>
        /// <param name="e">Details about the event.</param>
        private void buttonClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Handler for the timer thread
        /// Refresh the list of service states
        /// </summary>
        /// <param name="sender">Source of the event.</param>
        /// <param name="e">Details about the event.</param>
        private void TimerTick(object sender, EventArgs e)
        {
            this.UpdateServiceState();
        }

        /// <summary>
        /// Handler for the "activated" event
        /// Send the main window to the undermost position
        /// </summary>
        /// <param name="sender">Source of the event.</param>
        /// <param name="e">Details about the event.</param>
        private void FormActivated(object sender, EventArgs e)
        {
            this.SendToBack();
        }


        
        // Handler for the "Move Point" button

        Point movePoint;

        /// <summary>
        /// Handle the mouse down event of the "Move Point" button
        /// Store the current cursor position
        /// </summary>
        /// <param name="sender">Source of the event.</param>
        /// <param name="e">Mouse move event.</param>
        private void MoveMouseDown(object sender, MouseEventArgs e)
        {
            this.movePoint = Cursor.Position;
        }

        /// <summary>
        /// Handle the mouse up event of the "Move Point" button
        /// Move the window to the currunt cursor position
        /// </summary>
        /// <param name="sender">Source of the event.</param>
        /// <param name="e">Mouse move event.</param>
        private void MoveMouseUp(object sender, MouseEventArgs e)
        {
            Point p = new Point(this.DesktopLocation.X + (Cursor.Position.X - this.movePoint.X), 
                                this.DesktopLocation.Y + (Cursor.Position.Y - this.movePoint.Y) );
            this.DesktopLocation = p;
        }
    }
}